/**
 * Promise
 * 
 * 三种状态（pending、fulfilled、rejected）和 如何正确地处理这些状态
 * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
 */

// 函数方式
function myPromise() {

}


// 类方式
class myPromise {

  constructor(executer) {
    this.status = 'pending';// fulfilled, rejected
    this.value = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];


    const resolve = (value) => {
      if (this.status === 'pending') {
        this.status = 'fulfilled';
        this.value = value;
        this.onFulfilledCallbacks.forEach(fn => fn())
      }

    }

    const reject = (reason) => {
      if (this.status === 'pending') {
        this.status = 'rejected';
        this.reason = reason;
        this.onRejectedCallbacks.forEach(fn => fn())
      }
    }

    try {
      executer(resolve, reject)
    } catch (err) {
      reject(err)
    }

  }

  // 成功时回调
  then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; };

  }

  // 失败时回调
  catch(onrejected) {

  }
}



new Promise((resolve, reject) => {
  let a = 2;
  if (a + 4 < 3) {
    resolve('success')

  } else {
    reject('failed')
  }
}).then((res) => {
  //
}, (err) => { }).catch((err) => {

})